<template>
	<view>
		<view class="uni-header">
			<view class="uni-group">
				<view class="uni-title"></view>
				<view class="uni-sub-title"></view>
			</view>
			<view class="uni-group">
				<input class="uni-search" type="text" v-model="query" placeholder="请输入搜索内容" />
				<button class="uni-button" type="default" size="mini" @click="search">搜索</button>
				<button class="uni-button" type="primary" size="mini" @click="add('add')">添加歌曲</button>
			</view>
		</view>
		<view class="uni-container">
			<unicloud-db ref="udb" :collection="collectionName" :options="options" :where="where" field=""
				page-data="replace" :orderby="orderby" :getcount="true" :page-size="options.pageSize"
				:page-current="options.pageCurrent" v-slot:default="{ data, pagination, loading, error }">
				<uni-table :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe>
					<uni-tr>
						<uni-th align="center">序号</uni-th>
						<uni-th align="center">歌曲</uni-th>
						<uni-th align="center">答案1</uni-th>
						<uni-th align="center">答案2</uni-th>
						<uni-th align="center">答案3</uni-th>

						<uni-th width="170" align="center">创建时间</uni-th>
						<uni-th width="204" align="center">操作</uni-th>
					</uni-tr>
					<uni-tr v-for="(item, index) in data" :key="index">
						<uni-td align="center">{{ index + 1 }}</uni-td>
						<uni-td align="center">
							<audio :src="item.url" controls></audio>
						</uni-td>
						<uni-td align="center">{{ item.daan1 }}{{item.correct==1?'(正确答案)':''}}</uni-td>
						<uni-td align="center">{{ item.daan2 }}{{item.correct==2?'(正确答案)':''}}</uni-td>
						<uni-td align="center">{{ item.daan3 }}{{item.correct==3?'(正确答案)':''}}</uni-td>
						<uni-td align="center">
							<uni-dateformat :date="item.createtime * 1000" :threshold="[0, 0]" />
						</uni-td>
						<uni-td align="center">
							<view class="uni-group">
								<button @click="add('change', item)" class="uni-button" size="mini"
									type="warn">修改</button>
								<button @click="confirmDelete(item)" class="uni-button" size="mini"
									type="warn">删除</button>
							</view>
						</uni-td>
					</uni-tr>
				</uni-table>
				<view class="uni-pagination-box">
					<uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current"
						:total="pagination.count" @change="onPageChanged" />
				</view>
			</unicloud-db>

			<uni-popup ref="addtaskPopup" type="center">
				<view class="modal" style="width:500px; padding: 20px;">
					<view class="uni-container">
						<uni-forms ref="form" validateTrigger="bind">
							<uni-forms-item label="请上传歌曲" name="title" labelWidth="100">
								<button type="primary" size="mini" @click="select">选择歌曲</button>
							</uni-forms-item>
							<uni-forms-item label="歌曲" name="title" labelWidth="100" v-if="audiodata.url!=''">
								<audio :src="audiodata.url" controls></audio>
							</uni-forms-item>
							<uni-forms-item label="答案1" name="title" labelWidth="100">
								<input class="uni-input-border" type="text" placeholder="请输入答案1"
									v-model="audiodata.daan1" />
							</uni-forms-item>
							<uni-forms-item label="答案2" name="title" labelWidth="100">
								<input class="uni-input-border" type="text" placeholder="请输入答案2"
									v-model="audiodata.daan2" />
							</uni-forms-item>

							<uni-forms-item label="答案3" name="title" labelWidth="100">
								<input class="uni-input-border" type="text" placeholder="请输入答案3"
									v-model="audiodata.daan3" />
							</uni-forms-item>

							<uni-forms-item label="正确答案" name="title" labelWidth="100">
								<input class="uni-input-border" type="number" placeholder="请输入正确答案序号"
									v-model="audiodata.correct" />
							</uni-forms-item>

							<view class="uni-button-group pointer">
								<button class="uni-button uni-button-full" type="primary" :disabled="isLoading"
									@click="save">保存</button>
							</view>
						</uni-forms>
					</view>
				</view>
			</uni-popup>

			<uni-popup ref="dialogpopup" type="dialog">
				<uni-popup-dialog mode="base" title="是否确认删除" :duration="2000" @close="close" @confirm="confirm">
				</uni-popup-dialog>
			</uni-popup>
		</view>
	</view>
</template>

<script>
	const db = uniCloud.database();
	// 表查询配置
	const dbCollectionName = 'songlist';
	const dbOrderBy = 'createtime desc'; // 排序字段
	const dbSearchFields = ['_id', 'daan1', 'daan2', 'daan3']; // 支持模糊搜索的字段列表
	// 分页配置
	const pageSize = 10;
	const pageCurrent = 1;

	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				isLoading: false,
				query: '',
				where: '',
				orderby: dbOrderBy,
				collectionName: dbCollectionName,
				options: {
					pageSize,
					pageCurrent
				},
				audiodata: {
					url: "",
					daan1: '',
					daan2: '',
					daan3: '',
					correct: null
				},
				type: 'change',
				delid: ''
			};
		},
		computed: {
			...mapState('user', ['userInfo'])
		},
		methods: {
			getWhere() {
				const query = this.query.trim();
				if (!query) {
					return '';
				}
				const queryRe = new RegExp(query, 'i');
				return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ');
			},
			search() {
				const newWhere = this.getWhere();
				const isSameWhere = newWhere === this.where;
				this.where = newWhere;
				if (isSameWhere) {
					// 相同条件时，手动强制刷新
					this.loadData();
				}
			},
			loadData(clear = true) {
				this.$refs.udb.loadData({
					clear
				});
			},
			onPageChanged(e) {
				this.$refs.udb.loadData({
					current: e.current
				});
			},
			add(type, item) {
				this.type = type;
				if (type == 'change') {
					this.audiodata = item;
				}
				this.$refs.addtaskPopup.open();
			},

			confirmDelete(item) {
				this.delid = item._id;
				this.$refs.dialogpopup.open();
			},
			save() {
				if (this.audiodata['daan1'] == '') {
					uni.showToast({
						title: '请输入答案1',
						duration: 2000,
						icon: 'none'
					});
					return;
				}
				if (this.audiodata['daan2'] == '') {
					uni.showToast({
						title: '请输入答案2',
						duration: 2000,
						icon: 'none'
					});
					return;
				}
				if (this.audiodata['daan3'] == '') {
					uni.showToast({
						title: '请输入答案3',
						duration: 2000,
						icon: 'none'
					});
					return;
				}
				if (Number(this.audiodata['correct']) <= 0 || Number(this.audiodata['correct']) > 3) {
					uni.showToast({
						title: '请输入正确答案',
						duration: 2000,
						icon: 'none'
					});
					return;
				}

				if (this.audiodata['url'] == '') {
					uni.showToast({
						title: '请上传歌曲',
						duration: 2000,
						icon: 'none'
					});
					return;
				}

				this.isLoading = true;
				console.log("this.type: ",this.type);
				this.audiodata['caozuo'] = this.type;
				console.log(this.audiodata);
				uni.showLoading({
					title: '保存中'
				});
				uniCloud.callFunction({
					name: 'uni-admin',
					data: {
						action: "admin/createaudio",
						data:this.audiodata
					}
				}).then((res) => {
					console.log(res, "add---update--------------")
					uni.hideLoading();
					this.isLoading = false;
					if (res.result.errcode != 0) {
						uni.showToast({
							title: res.errmsg,
							duration: 2000,
							icon: 'none'
						});
						return;
					}else{
						uni.showToast({
							title: this.type == 'add'?'添加成功':'修改成功',
							duration: 2000,
							icon: 'none'
						});
					}
					this.$refs.addtaskPopup.close();
					this.loadData();
					this.audiodata['daan1'] = '';
					this.audiodata['url'] = '';
					this.audiodata['daan2'] = '';
					this.audiodata['daan3'] = '';
					this.audiodata['correct'] = null;
				}).catch((res) => {
					console.log(res)
					uni.hideLoading();
				}).finally(err => {
					this.isLoading = false;
					uni.hideLoading();
				})
				// this.$request('admin/createaudio', this.audiodata)
				// 	.then(res => {
				// 		this.isLoading = false;
				// 		if (res.errcode != 0) {
				// 			uni.showToast({
				// 				title: res.errmsg,
				// 				duration: 2000,
				// 				icon: 'none'
				// 			});
				// 			return;
				// 		}
				// 		this.$refs.addtaskPopup.close();
				// 		this.loadData();
				// 		this.audiodata['daan1'] = '';
				// 		this.audiodata['url'] = '';
				// 		this.audiodata['daan2'] = '';
				// 		this.audiodata['daan3'] = '';
				// 		this.audiodata['correct'] = null;
				// 	})
				// 	.catch(err => {
				// 		this.isLoading = false;
				// 	});
			},
			close() {
				this.$refs.dialogpopup.close();
			},
			confirm() {
				uni.showLoading({
					title: '处理中'
				});
				uniCloud.callFunction({
					name: 'uni-admin',
					data: {
						action: "admin/delaudio",
						data: {
							id: this.delid
						}
					}
				}).then((res) => {
					console.log(res, "update--------------")
					uni.hideLoading();
					uni.showToast({
						title: '删除成功',
						duration: 2000,
						icon: 'none'
					});
					this.$refs.dialogpopup.close();
					this.loadData();
				}).catch((res) => {
					console.log(res)
				}).finally(err => {
					uni.hideLoading();
				})
				// this.$request('admin/delaudio', {
				// 		id: this.delid
				// 	})
				// 	.then(res => {
				// 		uni.showToast({
				// 			title: '删除成功',
				// 			duration: 2000,
				// 			icon: 'none'
				// 		});
				// 		this.$refs.dialogpopup.close();
				// 		this.loadData();
				// 	})
				// 	.catch(err => {});
			},
			select() {
				var self = this
				uni.chooseFile({
					count: 1,
					extension: ['.mp3'],
					success(res) {
						// tempFilePath可以作为img标签的src属性显示图片
						console.log(res);
						const tempFilePaths = res.tempFiles;
						console.log(tempFilePaths);

						uniCloud.uploadFile({
							filePath: res.tempFilePaths[0],
							cloudPath: tempFilePaths[0]['name'],
							success: res1 => {
								console.log(res1.fileID);
								self.audiodata['url'] = res1.fileID
							}
						});
					}
				});
			}
		}
	};
</script>
<style>
	.modal {
		width: 100%;
		max-width: 980px;
		margin: 0 auto;
		background-color: #ffffff;
	}

	.modal-content {
		padding: 15px;
		height: 500px;
		box-sizing: border-box;
	}

	.password-popup {
		padding: 30px;
	}

	.radio {
		margin-right: 25px;
	}

	.uni-padding-wrap {
		overflow: hidden;
		padding-bottom: 22px;
	}

	.uni-title {
		font-size: 14px;
		width: 100px;
		justify-content: flex-start;
		display: flex;
		margin-right: 50px;
		float: left;
		height: 36px;
		line-height: 36px;
		color: #606266 !important;
	}

	uni-radio-group {
		display: flex;
		float: left;
	}
</style>
